package com.example.piece.ui.activity

import android.Manifest
import android.graphics.Bitmap
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.text.Editable
import android.text.TextWatcher
import android.util.Log
import android.view.View
import android.widget.ImageView
import android.widget.LinearLayout
import androidx.annotation.RequiresApi
import androidx.appcompat.widget.AppCompatEditText
import androidx.databinding.DataBindingUtil
import androidx.databinding.ViewDataBinding
import androidx.recyclerview.widget.RecyclerView
import androidx.viewpager.widget.ViewPager
import com.bumptech.glide.Glide
import com.bumptech.glide.request.target.SimpleTarget
import com.bumptech.glide.request.transition.Transition
import com.example.base.aop.click.RepeatClick
import com.example.base.aop.login.LoginCallback
import com.example.base.aop.permission.PermissionRequest
import com.example.base.broadcast.Event
import com.example.base.broadcast.EventBusUtil
import com.example.base.ext.*
import com.example.base.popup.util.KeyboardUtils
import com.example.base.tools.JsonTool
import com.example.base.ui.activity.BaseActivity
import com.example.base.vm.onError
import com.example.piece.R
import com.example.piece.constant.Key
import com.example.piece.constant.RoutePath
import com.example.piece.databinding.ActivityPlayVideoBinding
import com.example.piece.databinding.ItemTikTokBinding
import com.example.piece.entity.AttentionEntity
import com.example.piece.tools.ShareUtil
import com.example.piece.tools.UtilsPlay
import com.example.piece.tools.cache.PreloadManager
import com.example.piece.ui.adapter.PingLunNodeAdapter
import com.example.piece.ui.adapter.TiktokAdapter
import com.example.piece.ui.view.VerticalViewPager
import com.example.piece.ui.view.controller.TikTokController
import com.example.piece.ui.view.render.TikTokRenderViewFactory
import com.example.piece.vm.HelperViewModel
import com.example.piece.vm.JokesViewModel
import com.example.piece.vm.UserViewModel
import com.kongzue.dialogx.dialogs.BottomDialog
import com.kongzue.dialogx.dialogs.MessageDialog
import com.kongzue.dialogx.dialogs.TipDialog
import com.kongzue.dialogx.dialogs.WaitDialog
import com.kongzue.dialogx.interfaces.OnBackPressedListener
import com.kongzue.dialogx.interfaces.OnBindView
import com.kongzue.dialogx.interfaces.OnDialogButtonClickListener
import com.therouter.router.Autowired
import com.therouter.router.Route
import com.wenming.library.encryption.imp.AESEncode
import kotlinx.coroutines.Deferred
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.async
import kotlinx.coroutines.runBlocking
import xyz.doikki.videoplayer.player.AbstractPlayer
import xyz.doikki.videoplayer.player.VideoView
import xyz.doikki.videoplayer.util.L
import java.io.File

/*
* 视频播放页面
* */

@Route(path = RoutePath.PLAY_VIDEO)
class PlayVideoActivity : BaseActivity<ActivityPlayVideoBinding>() {
    @JvmField
    @Autowired(name = Key.DataKey.IDS)
    var IDS: String = ""

    @JvmField
    @Autowired(name = Key.DataKey.IDS_POSITION)
    var IdsPosition = -1
    private var mCurPos = -1
    private val mVideoList = mutableListOf<AttentionEntity>()
    private var mTiktok2Adapter: TiktokAdapter? = null
    private var mViewPager: VerticalViewPager? = null

    private var mPreloadManager: PreloadManager? = null

    private var mController: TikTokController? = null

    protected var mVideoView: VideoView<AbstractPlayer>? = null

    override fun getContentRes(): Int = R.layout.activity_play_video
    private val helperViewModel: HelperViewModel by lazy {
        getViewModel<HelperViewModel>()
    }
    private val jokesViewModel: JokesViewModel by lazy {
        getViewModel<JokesViewModel>()
    }
    private val userViewModel: UserViewModel by lazy {
        getViewModel<UserViewModel>()
    }

    override fun initData(savedInstanceState: Bundle?) {
        super.initData(savedInstanceState)

        initViewPager()
        initVideoView()
        mPreloadManager = PreloadManager.getInstance(this)


        getVideoData()
    }

    //获取数据
    private fun getVideoData() {
        jokesViewModel.jokesVideoListIds(null, IDS) {
            if (it.code == 200) {

                val data = it.data;
                mVideoList.addAll(data)
                mTiktok2Adapter?.notifyDataSetChanged()
                if (mCurPos == -1) {
                    mViewPager?.setCurrentItem(IdsPosition)

                    mViewPager?.post(Runnable {
                        startPlay(IdsPosition)
                    })

                }


            } else {
                TipDialog.show(it.msg)

            }


        } onError {
            TipDialog.show(it)

        }
    }

    private fun initVideoView() {
        mVideoView = this?.let { VideoView<AbstractPlayer>(it) }
        mVideoView?.setLooping(true)

        //以下只能二选一，看你的需求
        mVideoView?.setRenderViewFactory(TikTokRenderViewFactory.create())
        // mVideoView?.setScreenScaleType(VideoView.SCREEN_SCALE_CENTER_CROP);
        mController = this?.let { TikTokController(it) }
        mVideoView?.setVideoController(mController)
    }

    private fun initViewPager() {
        mViewPager = mBinding.vvp
        mViewPager?.setOffscreenPageLimit(4)
        mTiktok2Adapter = TiktokAdapter(mVideoList, object : View.OnClickListener {
            override fun onClick(v: View?) {
                val position: Int = v?.tag as Int
                when (v?.id) {
                    R.id.tv_like -> {

                        mTiktok2Adapter?.data?.get(position)?.let { clickLike(it, v) }

                    }
                    R.id.tv_pinglun -> {
                        mTiktok2Adapter?.data?.get(position)?.let { goToPL(it) }


                    }
                    R.id.tv_share -> {
                        mTiktok2Adapter?.data?.get(position)?.let { clickShare(it) }
                    }

                }
            }

        })
        mViewPager?.setAdapter(mTiktok2Adapter)
        mViewPager?.setOverScrollMode(View.OVER_SCROLL_NEVER)
        mViewPager?.setOnPageChangeListener(object : ViewPager.SimpleOnPageChangeListener() {
            private var mCurItem = 0

            /**
             * VerticalViewPager是否反向滑动
             */
            private var mIsReverseScroll = false
            override fun onPageScrolled(
                position: Int,
                positionOffset: Float,
                positionOffsetPixels: Int,
            ) {
                super.onPageScrolled(position, positionOffset, positionOffsetPixels)
                if (position == mCurItem) {
                    return
                }
                mIsReverseScroll = position < mCurItem
            }

            override fun onPageSelected(position: Int) {
                super.onPageSelected(position)
                if (position == mCurPos) return
                startPlay(position)

                if (position == mVideoList.size - 1) {
                    getVideoData()
                }
            }

            override fun onPageScrollStateChanged(state: Int) {
                super.onPageScrollStateChanged(state)
                if (state == VerticalViewPager.SCROLL_STATE_DRAGGING) {
                    mCurItem = mViewPager?.getCurrentItem()!!
                }
                if (state == VerticalViewPager.SCROLL_STATE_IDLE) {
                    mPreloadManager?.resumePreload(mCurPos, mIsReverseScroll)
                } else {
                    mPreloadManager?.pausePreload(mCurPos, mIsReverseScroll)
                }
            }
        })
    }

    @LoginCallback
    @RepeatClick
    fun clickLike(
        item: AttentionEntity,
        view: View,
    ) {
        /* if (App.USER_TOKEN.isNullOrEmpty()) {//未登录
             gotoLogin()
         } else {*/
        jokesViewModel.jokesLike(this@PlayVideoActivity,
            item.joke.jokesId,
            (!item.info.isLike).toString()) {
            if (it.code == 200) {
                item.info.isLike = !item.info.isLike
                if (item.info.isLike) {
                    item.info.likeNum = item.info.likeNum + 1
                } else {
                    item.info.likeNum = item.info.likeNum - 1
                }
                view.isSelected = item.info.isLike

                // notifyItemChanged(helper.layoutPosition, 0)


            } else {
                this@PlayVideoActivity.toast(it.msg)

            }
        } onError {

        }
        // }
    }

    @RepeatClick
    fun goToPL(item: AttentionEntity) {
        BottomDialog.build()
            .setCustomView(object : OnBindView<BottomDialog>(R.layout.dialog_pinglun) {
                override fun onBind(dialog: BottomDialog?, v: View?) {
                    val rvPl = v?.findViewById<RecyclerView>(R.id.rv_pl)
                    v?.findViewById<ImageView>(R.id.img_close)?.setOnClickListener {
                        dialog?.dismiss()

                    }


                    val pingLunNodeAdapter =
                        PingLunNodeAdapter(userViewModel,
                            jokesViewModel,
                            this@PlayVideoActivity as BaseActivity<ViewDataBinding>)
                    rvPl?.adapter = pingLunNodeAdapter
                    pingLunNodeAdapter.setEmptyView(R.layout.layout_empty)
                    var page = 1

                    pingLunNodeAdapter.loadMoreModule.isAutoLoadMore = true
                    pingLunNodeAdapter.loadMoreModule.isEnableLoadMoreIfNotFullPage = true
                    pingLunNodeAdapter.loadMoreModule.setOnLoadMoreListener {
                        page++
                        getPLList(item, page, pingLunNodeAdapter)

                    }

                    getPLList(item, page, pingLunNodeAdapter)
                    v?.findViewById<LinearLayout>(R.id.ll_pl)?.setOnClickListener {

                        /*  if (App.USER_TOKEN.isNullOrEmpty()) {//未登录
                              gotoLogin()
                          } else {*/
                        BottomDialog.show(object :
                            OnBindView<BottomDialog>(R.layout.dialog_pinglun_write) {
                            override fun onBind(dialog: BottomDialog?, v: View?) {
                                val etPL = v?.findViewById<AppCompatEditText>(R.id.et_pl)
                                etPL?.postDelayed({ KeyboardUtils.open(etPL) }, 100)
                                val imgSend = v?.findViewById<ImageView>(R.id.img_send)
                                etPL?.addTextChangedListener(object : TextWatcher {
                                    override fun beforeTextChanged(
                                        s: CharSequence?,
                                        start: Int,
                                        count: Int,
                                        after: Int,
                                    ) {
                                    }

                                    override fun onTextChanged(
                                        s: CharSequence?,
                                        start: Int,
                                        before: Int,
                                        count: Int,
                                    ) {
                                        imgSend?.isSelected = !s.isNullOrEmpty()
                                    }

                                    override fun afterTextChanged(s: Editable?) {

                                    }
                                })

                                imgSend?.setOnClickListener {
                                    if (!etPL?.text.toString().isNullOrEmpty()) {//提交评论
                                        jokesViewModel.jokesComment(this@PlayVideoActivity,
                                            item.joke.jokesId,
                                            etPL?.text.toString()) {
                                            if (it.code == 200) {
                                                val data = it.data
                                                pingLunNodeAdapter.addData(listOf(data))
                                                dialog?.dismiss()
                                            } else {
                                                toast(it.msg)
                                            }

                                        } onError {
                                            toast(it)
                                        }
                                    }

                                }


                            }

                        }).isAllowInterceptTouch = false
                    }

                }
                // }

            })
            .show()
    }

    private fun getPLList(
        item: AttentionEntity,
        page: Int,
        pingLunNodeAdapter: PingLunNodeAdapter,
    ) {
        jokesViewModel.jokesCommentList(this@PlayVideoActivity,
            item.joke.jokesId,
            page.toString()) {
            if (it.code == 200) {
                if (it.data.comments.isNullOrEmpty()) {
                    pingLunNodeAdapter.loadMoreModule.isEnableLoadMore = false
                    pingLunNodeAdapter.loadMoreModule.isAutoLoadMore = false
                    return@jokesCommentList
                }
                if (page === 1) {
                    pingLunNodeAdapter.setList(it.data.comments)

                } else {
                    pingLunNodeAdapter.addData(it.data.comments)

                }
            } else {
                this@PlayVideoActivity.toast(it.msg)

            }
        } onError {
            toast(it)

        }
    }

    @RepeatClick
    fun clickShare(item: AttentionEntity) {
        BottomDialog.build()
            .setCustomView(object : OnBindView<BottomDialog>(R.layout.dialog_share) {
                override fun onBind(dialog: BottomDialog?, v: View?) {
                    v?.findViewById<ImageView>(R.id.img_wx)?.setOnClickListener { //微信
                        this@PlayVideoActivity?.let { it1 ->
                            ShareUtil.shareTextToWechat(it1,
                                "测试")
                        }

                    }
                    v?.findViewById<ImageView>(R.id.img_pyq)?.setOnClickListener { //朋友圈
                        getphoto()

                    }
                    v?.findViewById<ImageView>(R.id.img_qq)?.setOnClickListener { //QQ
                        this@PlayVideoActivity?.let { it1 ->
                            ShareUtil.shareTextToQQFriend(it1,
                                "测试")
                        }

                    }
                    v?.findViewById<ImageView>(R.id.img_zone)?.setOnClickListener { //空间

                    }
                    v?.findViewById<ImageView>(R.id.img_vb)?.setOnClickListener { //微博
                        this@PlayVideoActivity?.let { it1 -> ShareUtil.shareTextToVB(it1, "测试") }

                    }
                    v?.findViewById<ImageView>(R.id.img_shoucang)?.setOnClickListener { //收藏
                        //首先判断是否收藏

                        jokesViewModel.jokesIsCollect(this@PlayVideoActivity, item.joke.jokesId) {
                            if (it.code == 200) {

                                jokesViewModel.jokesCollect(this@PlayVideoActivity,
                                    item.joke.jokesId,
                                    (!it.data.is_collect).toString()) { it1 ->
                                    if (it1.code == 200) {
                                        if (it.data.is_collect) {//取消成功 移除
                                            /*   if (isRemove) {
                                                   remove(item)

                                               }*/
                                            EventBusUtil.sendEvent(Event(Key.EventKey.EVENT_USERINFO_SC,
                                                -1L))
                                        } else {
                                            EventBusUtil.sendEvent(Event(Key.EventKey.EVENT_USERINFO_SC,
                                                1L))
                                        }
                                        dialog?.dismiss()

                                    } else {
                                        this@PlayVideoActivity.toast(it.msg)

                                    }
                                    this@PlayVideoActivity.toast(it1.msg)
                                } onError {
                                    this@PlayVideoActivity.toast(it)

                                }
                            } else {
                                this@PlayVideoActivity.toast(it.msg)

                            }
                        } onError {
                            this@PlayVideoActivity.toast(it)

                        }


                    }
                    v?.findViewById<ImageView>(R.id.img_copy)?.setOnClickListener { //复制
                        helperViewModel.helperJokeShare(this@PlayVideoActivity, item.joke.jokesId) {
                            if (it.code == 200) {
                                val entity = it.data
                                setClipboardContent(entity.share_title + "\n" + entity.share_content + "\n" + entity.share_url + "\n" + entity.share_img)
                                dialog?.dismiss()
                                this@PlayVideoActivity.toast("复制成功")

                            } else {
                                this@PlayVideoActivity.toast(it.msg)

                            }
                        } onError {
                            this@PlayVideoActivity.toast(it)


                        }
                    }
                    v?.findViewById<ImageView>(R.id.img_jb)?.setOnClickListener { //举报
                        navigationTo(RoutePath.MAIN_JUBAO_ACTIVITY)
                        dialog?.dismiss()

                    }
                    v?.findViewById<ImageView>(R.id.img_xq)?.setOnClickListener { //详情
                        this@PlayVideoActivity.navigationTo(RoutePath.MAIN_DETAIL_ACTIVITY,
                            mutableMapOf(
                                Key.DataKey.H5_TITLE to "帖子详情",
                                Key.DataKey.ITEM_DETAIL to JsonTool.object2Json(item))

                        )

                        dialog?.dismiss()
                    }
                }

            })
            .show()
    }

    /**  点击添加图片的事件  **/
    @PermissionRequest(
        value = [
            Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE,
        ]
    )
    private fun getphoto() {
        this@PlayVideoActivity?.let { it1 ->
            //要在子线程中使用，否则会报错
            val dataUri = ArrayList<Uri>()
            val dataDeferred = ArrayList<Deferred<Int>>()

            var waitId = 0;
            var progress = 0F
            WaitDialog.show("正在加载", WaitDialog.TYPE.NONE).setOnBackPressedListener(object :
                OnBackPressedListener {
                override fun onBackPressed(): Boolean {
                    MessageDialog.show("正在进行", "是否取消？", "是", "否")
                        .setOkButton(object : OnDialogButtonClickListener<MessageDialog> {
                            override fun onClick(baseDialog: MessageDialog, v: View?): Boolean {

                                waitId = -1
                                WaitDialog.dismiss()
                                return false
                            }


                        })
                    return false
                }

            })

            runBlocking {
                val data = ArrayList<String>()
                val dataFile = ArrayList<File>()

                data.add("http://jokes-avatar.cretinzp.com/qiniu/jokes/avatar/db85c776804b4daca3350ccc25179a3e.jpg")
             /*   data.add("http://wx2.sinaimg.cn/large/9bd522c1ly1gfg6zsy960g206s0aahe1.gif")
                data.add("http://wx4.sinaimg.cn/large/5eef6257gy1g8qmhbxeslg207s0dqx74.gif")
                data.add("http://juheimg.oss-cn-hangzhou.aliyuncs.com/joke/201602/19/32E90AB13A4841D3E1FC6233CED69B20.gif")
                data.add("http://wx4.sinaimg.cn/large/5eef6257gy1g8ttfjvbffg20690b4qv5.gif")
                data.add("https://gif.55.la/static/keyword/images/img2.gif")
                data.add("https://gif.55.la/static/keyword/images/img1.gif")
                data.add("https://gif.55.la/static/keyword/images/img4.gif")
                data.add("https://gif.55.la/static/keyword/images/img6.gif")*/
                for (i in 0 until data.size) {

                    val c1 = async(Dispatchers.IO) {
                        Glide.with(it1)
                            .asBitmap()
                            .load(data.get(i))
                            .into(object : SimpleTarget<Bitmap>() {
                                @RequiresApi(Build.VERSION_CODES.Q)
                                override fun onResourceReady(
                                    resource: Bitmap,
                                    transition: Transition<in Bitmap>?,
                                ) {
                                    val uri = resource.saveToGallery(this@PlayVideoActivity!!, resource)
                                    if (uri != null) {
                                        dataUri.add(uri)
                                        uri.uriToFileQ(this@PlayVideoActivity,uri)
                                            ?.let { dataFile.add(it) }
                                    }

                                    progress = (dataUri.size / data.size.toFloat())
                                    WaitDialog.show("正在加载" + ((progress * 100).toInt()).toString() + "%",
                                        progress)
                                    if (progress == 1f) {
                                        WaitDialog.dismiss()
                                        //  TipDialog.show(activity,"加载完成", WaitDialog.TYPE.SUCCESS,2000)


                                        if (dataUri.size > 0) {
                                            this@PlayVideoActivity?.let {
                                                ShareUtil.sharePictureToWechatFriendUri(it, dataUri, "")
                                                Log.e("TAG", "getFXData: .2222")
                                            }

                                        }
                                    } else {


                                    }
                                    Log.e("TAG", "getFXData: ." + dataUri.size)
                                }


                            })
                        1
                    }
                    dataDeferred.add(c1)

                }
                for (it in dataDeferred) {
                    it.await()
                }
            }


        }
    }

    private fun startPlay(position: Int) {
        val count: Int = mViewPager?.getChildCount() ?: 0
        for (i in 0 until count) {
            val itemView: View? = mViewPager?.getChildAt(i)
            if (itemView != null) {
                val binding = DataBindingUtil.getBinding<ItemTikTokBinding>(itemView)
                if (binding?.position === position) {
                    mVideoView?.release()
                    UtilsPlay.removeViewFormParent(mVideoView)
                    val attentionEntity: AttentionEntity = mVideoList[position]
                    val videoUrl =
                        AESEncode.Decrypt(
                            attentionEntity?.joke?.videoUrl?.split(",")?.get(0)
                                ?.replace("ftp://", "")
                                .toString().trim(),
                            "cretinzp**273846"
                        )
                    val playUrl: String? = mPreloadManager?.getPlayUrl(videoUrl)
                    L.i("startPlay: position: $position  url: $playUrl")
                    mVideoView?.setUrl(playUrl)
                    //请点进去看isDissociate的解释
                    mController?.addControlComponent(binding.tiktokView, true)
                    binding.container.addView(mVideoView, 0)
                    mVideoView?.start()
                    mCurPos = position
                    break
                }
            }


        }
    }


    override fun onResume() {
        super.onResume()
        if (mVideoView != null) {
            mVideoView?.resume()
        }
    }

    override fun onPause() {
        super.onPause()
        if (mVideoView != null) {
            mVideoView?.pause()
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        if (mVideoView != null) {
            mVideoView?.release()
        }

    }

}